package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.constant.CommonConstant;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.ContentDto;
import com.heima.model.wemedia.dtos.WmNewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsAuthResponse;
import com.heima.model.wemedia.pojos.NewsRequestDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.common.ThreadLocalUtils;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsVerifyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsVerifyService wmNewsVerifyService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    private WmUserMapper wmUserMapper;


    @Override
    public PageResponseResult list(NewsRequestDto dto) {
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId, ThreadLocalUtils.getUserId())
                .between(dto.getBeginPubdate() != null && dto.getEndPubdate() != null, WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate())
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                .like(dto.getKeyword() != null && !dto.getKeyword().equals(""), WmNews::getTitle, dto.getKeyword())
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .orderByDesc(WmNews::getPublishTime);
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        page(page, queryWrapper);
        long total = page.getTotal();
        List<WmNews> records = page.getRecords();
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), total);
        pageResponseResult.setData(records);
        return pageResponseResult;
    }

    @Override
    public ResponseResult submit(WmNews wmNews) throws Exception {
        wmNews.setUserId(ThreadLocalUtils.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        String content = wmNews.getContent();//文章内容
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);//文章内容
        List<String> images = null;///文章封面
        List<String> contentImages = new ArrayList<>();//内容图片
        for (ContentDto contentDto : contentDtos) {//遍历文章内容,获取到内容中的图片
            if (contentDto.getType().equals(ContentDto.IMAGE)) {
                //是图片
                contentImages.add(contentDto.getValue());
            }
        }
        //判断封面是否选择自动
        if (wmNews.getType() == -1) {
            //封面自动
            if (contentImages.isEmpty()) {
                //没有图片,设置布局为无图
                images = new ArrayList<>();
                wmNews.setType((short) 0);
            } else {
                if (contentImages.size() >= 3) {
                    //超过三张,取前三张
                    images = contentImages.stream().limit(3).collect(Collectors.toList());
                    wmNews.setType((short) 3);
                } else {
                    images = contentImages.stream().limit(1).collect(Collectors.toList());
                    wmNews.setType((short) 1);
                }
            }
            wmNews.setImages(StringUtils.join(images, ","));//文章封面图片用逗号分隔
        } else {
            //选择的是单图,三图或者无图
            String images1 = wmNews.getImages();//获取文章封面
            images = JSON.parseArray(images1, String.class);//转为集合
            wmNews.setImages(StringUtils.join(images, ","));
        }
        //判断是修改还是新增
        if (wmNews.getId() == null) {
            //新增
            save(wmNews);
        } else {
            //修改
            updateById(wmNews);
        }
        //如果是提交审核,添加素材和文章的关系
        if (wmNews.getStatus() == WmNews.Status.SUBMIT.getCode()) {
            //4.如果是提交审核，建立文章和素材关系。
            // 4.1 文章id如何来,mp会自己返回
            // 素材id如何来，根据素材url查询素材id
            Integer newsId = wmNews.getId();
            //根据文章id删除文章和素材之前关系
            wmNewsMaterialMapper.delete(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId, newsId));
            //添加封面和素材的关系
            for (String image : images) {
                LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmMaterial::getUrl, image);
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(queryWrapper);
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setMaterialId(wmMaterial.getId());
                wmNewsMaterial.setNewsId(wmNews.getId());
                wmNewsMaterial.setType((short) 1);
                wmNewsMaterial.setOrd((short) 1);
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            }
            //添加内容图片与素材的关系
            for (String contentImage : contentImages) {
                LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmMaterial::getUrl, contentImage);
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(queryWrapper);
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setMaterialId(wmMaterial.getId());
                wmNewsMaterial.setNewsId(wmNews.getId());
                wmNewsMaterial.setType((short) 0);
                wmNewsMaterial.setOrd((short) 1);
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            }
            //审核文章,远程调用article服务
            wmNewsVerifyService.autoScan(wmNews);


            /*//生成文章详情页面,保存minio,将minio中详情页面地址更新到ap_article表
            wmNewsVerifyService.publish(wmNews);*/
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult<WmNews> one(Integer id) {
        WmNews wmNews = getById(id);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult down0rUp(WmNews wmNews) {
        updateById(wmNews);
        //发送消息到Kafka实现app端文章下架
        WmNews news = getById(wmNews.getId());
        kafkaTemplate.send(CommonConstant.TOPIC_DOWN_UP, String.valueOf(news.getArticleId()), String.valueOf(news.getEnable()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //判断文章是草稿还是已发布,已发布需要删除文章与素材的关系表
        WmNews wmNews = getById(id);
        if (wmNews.getStatus() == WmNews.Status.SUBMIT.getCode()) {
            //根据文章ID删除文章和素材的关系表
            LambdaQueryWrapper<WmNewsMaterial> queryWapper = new LambdaQueryWrapper<>();
            queryWapper.eq(WmNewsMaterial::getNewsId, id);
            wmNewsMaterialMapper.delete(queryWapper);
        }
        //删除自媒体文章
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult listVo(WmNewsAuthDto dto) {
        //分页
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //设置条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(dto.getTitle()), WmNews::getTitle, dto.getTitle())
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .orderByDesc(WmNews::getCreatedTime);
        page(page, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal());
        List<WmNews> records = page.getRecords();
        List<WmNewsAuthResponse> list = new ArrayList<>();
        for (WmNews record : records) {
            WmNewsAuthResponse authResponse = new WmNewsAuthResponse();
            WmUser wmUser = wmUserMapper.selectById(record.getUserId());
            BeanUtils.copyProperties(record, authResponse);
            authResponse.setAuthorName(wmUser.getName());
            list.add(authResponse);
        }
        responseResult.setData(list);
        return responseResult;
    }

    @Override
    public ResponseResult oneVo(Integer id) {
        WmNews wmNews = getById(id);
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        WmNewsAuthResponse authResponse = new WmNewsAuthResponse();
        BeanUtils.copyProperties(wmNews, authResponse);
        authResponse.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(authResponse);
    }
}
